package com.xzjt.web.exception;

import com.xzjt.common.exception.CustomException;
import com.xzjt.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @ClassName: GlobalExceptionHandler
 * @Author: yuandong
 * @Date 2021/10/9 9:00
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 请求参数异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ParamsException.class)
    public R paramsException(ParamsException e) {
        log.error("请求参数异常>>>>>>>>>>>", e);
        return R.paramsException();
    }




    // 捕捉shiro的异常
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AuthenticationException.class)
    public R handle401(ShiroException e) {
        return R.error("401", e.getMessage());
    }




    @ExceptionHandler(UnauthorizedException.class)
    public R handle403() {
        log.info("全局捕捉shiro权限不足异常>>>>>>>>>>>>>>>>");
        return R.error("403", "您的权限不足");
    }



    /**
     * 通用异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R publicException(Exception e) {

        log.warn("自定义通用异常......");

        if (e instanceof NoHandlerFoundException) {
            return R.notFound();
        } else if(e instanceof CustomException){

            return R.error(((CustomException) e).getCode(), e.getMessage());

        } else if(e instanceof InvalidTokenException){
            return R.tokenExpired();
        } else{
            return R.exception();
        }

    }
}
